#include "fileio.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 设置日志系统
void setup_logging() {
    printf(" 日志系统初始化完成\n");
}

// 记录操作日志
void log_operation(const char* operation, const char* target, const char* details) {
    FILE* log_file = fopen("log.log", "a");
    if (log_file == NULL) {
        printf("无法打开日志文件\n");
        return;
    }
    
    time_t now = time(NULL);
    struct tm* timeinfo = localtime(&now);
    char timestamp[20];
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", timeinfo);
    
    fprintf(log_file, "[%s] %s: %s - %s\n", timestamp, operation, target, details);
    fclose(log_file);
    
    printf(" 记录日志: %s %s %s\n", operation, target, details);
}

// 解析学生数据行
void parse_student_line(char* line, char* id, char* name) {
    char* token = strtok(line, ",");
    if (token) {
        strncpy(id, token, MAX_ID_LEN - 1);
        token = strtok(NULL, ",");
        if (token) {
            strncpy(name, token, MAX_NAME_LEN - 1);
        }
    }
}

// 解析课程数据行
void parse_course_line(char* line, char* id, char* name, char* type, 
                      int* hours, float* credit, int* max_enrollment) {
    char* token = strtok(line, ",");
    if (token) strncpy(id, token, MAX_ID_LEN - 1);
    
    token = strtok(NULL, ",");
    if (token) strncpy(name, token, MAX_NAME_LEN - 1);
    
    token = strtok(NULL, ",");
    if (token) strncpy(type, token, MAX_TYPE_LEN - 1);
    
    token = strtok(NULL, ",");
    if (token) *hours = atoi(token);
    
    token = strtok(NULL, ",");
    if (token) *credit = atof(token);
    
    token = strtok(NULL, ",");
    if (token) *max_enrollment = atoi(token);
}

// 从文件加载学生数据
int load_students_from_file(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        printf(" 学生数据文件 %s 不存在，将创建新文件\n", filename);
        return 0;
    }
    
    printf(" 从文件加载学生数据: %s\n", filename);
    
    char line[256];
    int loaded_count = 0;
    
    // 跳过标题行（如果有）
    if (fgets(line, sizeof(line), file)) {
        // 检查是否是标题行
        if (strstr(line, "学号") == NULL && strstr(line, "id") == NULL) {
            // 不是标题行，回退文件指针
            fseek(file, 0, SEEK_SET);
        }
    }
    
    while (fgets(line, sizeof(line), file)) {
        // 移除换行符
        line[strcspn(line, "\n")] = 0;
        
        if (strlen(line) == 0) continue;
        
        char id[MAX_ID_LEN] = {0};
        char name[MAX_NAME_LEN] = {0};
        
        parse_student_line(line, id, name);
        
        if (strlen(id) > 0 && strlen(name) > 0) {
            // 使用学生模块的函数添加学生
            extern int add_student(const char*, const char*);
            if (add_student(id, name)) {
                loaded_count++;
            }
        }
    }
    
    fclose(file);
    printf(" 从文件加载 %d 名学生数据\n", loaded_count);
    log_operation("LOAD_STUDENTS", filename, "从文件加载学生数据");
    return loaded_count;
}

// 从文件加载课程数据
int load_courses_from_file(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        printf(" 课程数据文件 %s 不存在，将创建新文件\n", filename);
        return 0;
    }
    
    printf(" 从文件加载课程数据: %s\n", filename);
    
    char line[256];
    int loaded_count = 0;
    
    // 跳过标题行（如果有）
    if (fgets(line, sizeof(line), file)) {
        // 检查是否是标题行
        if (strstr(line, "课程编号") == NULL && strstr(line, "id") == NULL) {
            // 不是标题行，回退文件指针
            fseek(file, 0, SEEK_SET);
        }
    }
    
    while (fgets(line, sizeof(line), file)) {
        // 移除换行符
        line[strcspn(line, "\n")] = 0;
        
        if (strlen(line) == 0) continue;
        
        char id[MAX_ID_LEN] = {0};
        char name[MAX_NAME_LEN] = {0};
        char type[MAX_TYPE_LEN] = {0};
        int hours = 0;
        float credit = 0.0;
        int max_enrollment = 0;
        
        parse_course_line(line, id, name, type, &hours, &credit, &max_enrollment);
        
        if (strlen(id) > 0 && strlen(name) > 0 && hours > 0 && credit > 0 && max_enrollment > 0) {
            // 使用课程模块的函数添加课程
            extern int add_course(const char*, const char*, const char*, int, float, int);
            if (add_course(id, name, type, hours, credit, max_enrollment)) {
                loaded_count++;
            }
        }
    }
    
    fclose(file);
    printf(" 从文件加载 %d 门课程数据\n", loaded_count);
    log_operation("LOAD_COURSES", filename, "从文件加载课程数据");
    return loaded_count;
}

// 保存学生数据到文件
int save_students_to_file(const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        printf(" 无法打开文件用于保存: %s\n", filename);
        return 0;
    }
    
    // 写入标题行
    fprintf(file, "学号,姓名,已选课程数,总学分\n");
    
    // 获取所有学生
    extern Student* get_all_students();
    extern int get_student_count();
    
    Student* students = get_all_students();
    int count = get_student_count();
    int saved_count = 0;
    
    for (int i = 0; i < count; i++) {
        fprintf(file, "%s,%s,%d,%.1f\n", 
                students[i].id, students[i].name, 
                students[i].course_count, students[i].total_credits);
        saved_count++;
    }
    
    fclose(file);
    printf(" 保存 %d 名学生数据到文件: %s\n", saved_count, filename);
    log_operation("SAVE_STUDENTS", filename, "保存学生数据到文件");
    return saved_count;
}

// 保存课程数据到文件
int save_courses_to_file(const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        printf(" 无法打开文件用于保存: %s\n", filename);
        return 0;
    }
    
    // 写入标题行
    fprintf(file, "课程编号,课程名称,课程性质,授课学时,学分,最大选课人数,当前选课人数\n");
    
    // 获取所有课程
    extern Course* get_all_courses();
    extern int get_course_count();
    
    Course* courses = get_all_courses();
    int count = get_course_count();
    int saved_count = 0;
    
    for (int i = 0; i < count; i++) {
        fprintf(file, "%s,%s,%s,%d,%.1f,%d,%d\n", 
                courses[i].id, courses[i].name, courses[i].type,
                courses[i].hours, courses[i].credit, 
                courses[i].max_enrollment, courses[i].current_enrollment);
        saved_count++;
    }
    
    fclose(file);
    printf("保存 %d 门课程数据到文件: %s\n", saved_count, filename);
    log_operation("SAVE_COURSES", filename, "保存课程数据到文件");
    return saved_count;
}
